<?php

class PaypalIpnController extends BrowseControllerBase {
	
	public function __construct() {
		parent::__construct ();
	
	}
	public function indexAction() {
		$settingsDataService = new SettingsDataService ();
		$config = $settingsDataService->getPaypalSettings ();
		$gateway = new PayPalGateway ( $config );
		$gateway->setConfig ( $config );
		$inp = $this->getPost ();
		
		$gateway->getGateway ()->getLog ()->log ( '\n ' . print_r ( $inp, true ) . " \n " . print_r ( $_GET, true ), Zend_Log::INFO );
		
		if (! isset ( $_GET ['order_id'] ))
			return;
		$order_id = $_GET ['order_id'];
		
		unset ( $inp ['authen'] );
		unset ( $inp ['control'] );
		unset ( $inp ['action'] );
		
		$parsedUrl = parse_url ( $gateway->getGatewayUrl () );
		$postString = http_build_query ( array_merge ( array ('cmd' => '_notify-validate' ), $inp ), '', '&' );
		
		try {
			if (empty ( $parsedUrl ['path'] )) {
				$parsedUrl ['path'] = '/';
			}
			
			// Open socket
			$fp = fsockopen ( $parsedUrl ['host'], 80, $errNum, $errStr, 30 );
			
			if (! $fp) {
				$gateway->getGateway ()->getLog ()->log ( sprintf ( '\n ' . 'Unable to open socket: [%d] %s', $errNum, $errStr ) . print_r ( $inp, true ), Zend_Log::INFO );
			}
			
			stream_set_blocking ( $fp, true );
			fputs ( $fp, "POST {$parsedUrl['path']} HTTP/1.1\r\n" );
			fputs ( $fp, "Host: {$parsedUrl['host']}\r\n" );
			fputs ( $fp, "Content-type: application/x-www-form-urlencoded\r\n" );
			fputs ( $fp, "Content-length: " . strlen ( $postString ) . "\r\n" );
			fputs ( $fp, "Connection: close\r\n\r\n" );
			fputs ( $fp, $postString . "\r\n\r\n" );
			
			$gateway->getGateway ()->getLog ()->log ( '\n ' . print_r ( $inp, true ) . "\n" . 'order_id' . $order_id . "\n" . $postString, Zend_Log::INFO );
			$response = '';
			
			while ( ! feof ( $fp ) ) {
				$response .= fgets ( $fp, 1024 );
			
			}
			fclose ( $fp );
			
			if (! stripos ( $response, 'VERIFIED' )) {
				$gateway->getGateway ()->getLog ()->log ( '\n ' . sprintf ( 'IPN Validation Failed: %s %s', print_r ( $parsedUrl ['host'], true ), print_r ( $parsedUrl ['path'], true ) ) . print_r ( $inp, true ) . '\n' . $postString, Zend_Log::INFO );
				return false;
			}
			
			// Success!
			$gateway->getGateway ()->getLog ()->log ( '\n ' . 'IPN Validation Succeeded \n ' . print_r ( $inp, true ) . ' \n ' . $postString, Zend_Log::INFO );
			
			$transactionData = array ();
			
			$payment_status = $inp ['payment_status'];
			
			$payer_email = $inp ['payer_email'];
			$currency = $inp ['mc_currency'];
			$amount = $inp ['mc_gross'];
			$first_name = $inp ['first_name'];
			$last_name = $inp ['last_name'];
			$payment_date = date ( strtotime ( 'Y-m-d', $inp ['payment_date'] ) );
			$parent_transaction_id = $inp ['parent_txn_id'];
			$transaction_id = $inp ['txn_id'];
			
			$orderDataService = new PackageOrderDataService ();
			$orderEntity = $orderDataService->getById ( $order_id ); //
			if ($orderEntity == null) {
				$gateway->getGateway ()->getLog ()->log ( '\n ' . 'Can not order id ' . $order_id . ' :', Zend_Log::INFO );
				return false;
				/*
				 $orderPackageEntity = $orderDataService->beforeCreate();
				 $orderPackageEntity->transaction_id=$transaction_id;
				 $orderEntity = $orderDataService->create($orderPackageEntity);
				 */
			}
			$gateway->getGateway ()->getLog ()->log ( '\n ' . 'Find order id ' . $order_id . ' :', Zend_Log::INFO );
			$today = date ( 'Y-m-d', strtotime ( $orderEntity->expiredDate ) );
			$expiredDate = date ( 'Y-m-d', strtotime ( "$today + 1 months" ) );
			
			switch ($payment_status) {
				
				case 'Completed' :
					if (strtoupper ( $inp ['txn_type'] ) == strtoupper ( 'subscr_payment' )) {
						$orderEntity->status = PackageOrderEntity::COMPLETED;
						$orderEntity->expiredDate = $expiredDate;
						$orderEntity->modifiedDate = date ( 'Y-m-d' );
						$orderDataService->update ( $orderEntity );
						$gateway->getGateway ()->getLog ()->log ( '\n ' . 'payment success increate expiress date to :' . $expiredDate, Zend_Log::INFO );
						break;
					} else if (strtoupper ( $inp ['txn_type'] ) == strtoupper ( 'subscr_cancel' )) {
						$orderEntity->status = PackageOrderEntity::CANCELLED;
						$orderEntity->modifiedDate = date ( 'Y-m-d' );
						$orderDataService->update ( $orderEntity );
						$gateway->getGateway ()->getLog ()->log ( '\n ' . 'Cancel payment date: ' . date ( 'Y-m-d' ), Zend_Log::INFO );
						break;
					} else
						break;
				
				case 'Denied' :
				case 'Expired' :
				case 'Failed' :
				case 'Voided' :
					if (strtoupper ( $inp ['txn_type'] ) == strtoupper ( 'subscr_cancel' )) {
						$orderEntity->status = 'failed';
						$orderEntity->modifiedDate = date ( 'Y-m-d' );
						$orderDataService->update ( $orderEntity );
						$gateway->getGateway ()->getLog ()->log ( '\n ' . 'Cancel  fail date :' . date ( 'Y-m-d' ), Zend_Log::INFO );
						break;
					} else if (strtoupper ( $inp ['txn_type'] ) == strtoupper ( 'subscr_payment' )) {
						$gateway->getGateway ()->getLog ()->log ( '\n ' . 'payment fail date :' . date ( 'Y-m-d' ), Zend_Log::INFO );
						break;
					} else if (strtoupper ( $inp ['txn_type'] ) == strtoupper ( 'subscr_failed' )) {
						$gateway->getGateway ()->getLog ()->log ( '\n ' . 'payment failure :' . date ( 'Y-m-d' ), Zend_Log::INFO );
						break;
					} else
						break;
			
			}
		} catch ( Exception $ex ) {
			$gateway->getGateway ()->getLog ()->log ( '\n ' . 'Ipn Exception Handler: ' . $ex->__toString (), Zend_Log::ERR );
		}
	
	}
}